package cxydmmszl.chapter08.t137;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * <li style="color: red;">Prob</li>
 * 数组的 partition 调整
 * <li style="color: red;">Desc</li>
 *
 * <li style="color: red;">Link</li> CD36, CD37
 *
 * @author habitplus
 * @since 2021-09-06 21:32
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(bf.readLine());
        int[] arr = new int[n];
        String[] ss = bf.readLine().split(" ");

        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(ss[i]);
        }
        bf.close();

//        leftUnique(arr);
        partition(arr);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(arr[i]).append(" ");
        }
        System.out.println(sb.toString());
    }

    public static void leftUnique(int[] arr) {
        if (arr == null || arr.length < 1) {
            return;
        }

        // arr[0,pre] 是不重复且有序
        int pre = 0;

        for (int i = 1; i < arr.length; i++) {
            if (arr[i] != arr[pre]) {
                swap(arr, ++pre, i);
            }
        }

    }

    /*
        数组只有三种元素组成，假设为 0,1,2, 现要求将 0 全部放在最左边， 1 放中间， 2 放最右边
     */
    public static void partition(int[] arr) {
        if (arr == null || arr.length < 1) {
            return;
        }

        // arr[0, left] 全为 0
        // arr[right, n-1] 全为 2
        // arr[left+1, i] 全为 1
        int left = -1, right = arr.length, i = 0;

        while (i < right) {
            if (arr[i] == 0) {
                swap(arr, i++, ++left);
            } else if (arr[i] == 2) {
                swap(arr, i, --right);
            } else {
                i++;
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        if (i == j || arr[i] == arr[j]) return;
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}
